import { Button, Form, Input, message } from 'antd'
import React from 'react'
import { register } from '@/api/register'

interface RegisterUser {
    username: string
    password: string
    password2: string
}

async function onFinish(values: RegisterUser) {
    console.log(values)
    if (values.password !== values.password2) {
        message.error('两次密码不一致')
        return
    }
    try {
        const res: any = await register(values.username, values.password)
        if ([200, 201].includes(res.status)) {
            message.success('注册成功')
            console.log('注册接口返回 ===>', res)
            setTimeout(() => {
                window.location.href = '/login'
            }, 1 * 1000)
        }
    }
    catch (error: any) {
        console.log('error ===>', error)
    }
}

const layout1 = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
}

const layout2 = {
    labelCol: { span: 0 },
    wrapperCol: { span: 24 },
}

export default function Register() {
    return (
        <div className="text-16px ">
            <div className="mx-auto w-30% min-w-300px">
                <div className="text-center text-32px mb-20px">图书管理系统</div>
                <Form {...layout1} onFinish={onFinish} colon={false} autoComplete="off">
                    <Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名!' }]}>
                        <Input />
                    </Form.Item>

                    <Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码!' }]}>
                        <Input.Password />
                    </Form.Item>

                    <Form.Item label="确认密码" name="password2" rules={[{ required: true, message: '请输入确认密码!' }]}>
                        <Input.Password />
                    </Form.Item>

                    <Form.Item {...layout2}>
                        <div className="text-center">
                            <a href="/login">已有账号？去登录</a>
                        </div>
                    </Form.Item>

                    <Form.Item {...layout2}>
                        <Button className="w-100%" type="primary" htmlType="submit">
                            注册
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </div>
    )
}
